/**
 * 58.com Inc.
 * Copyright (c) 2005-2015 All Rights Reserved.
 */
package com.kld.common.framework.filter;

import com.kld.common.framework.global.Global;
import com.kld.common.util.DESCryptoTools;
import com.kld.common.util.PropertiesUtil;
import com.kld.common.util.SessionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author caozheng
 * @version 单点登录的拦截器
 */
public class SSOLoginFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(SSOLoginFilter.class);

    /**
     * @see Filter#init(FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    @SuppressWarnings("deprecation")
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        if (islogin(request)) {
            HttpSession httpSession = request.getSession(true);
            String authorized = request.getParameter("authorized");
            String username = request.getParameter("username");
            logger.info("auth===================>" + authorized);
            if("true".equals(PropertiesUtil.props.getProperty("debugMode"))){
                authorized="test";
            }
            if (StringUtils.isNotBlank(authorized)) {
                logger.info("用户名及ID" + authorized);
                String[] auth;
                String s_userid = "";
                String s_username = "";
                try {

                    if ("true".equals(PropertiesUtil.props.getProperty("debugMode"))) {
                        authorized = "userid=25,username=linsam0928";
                        username = "linsam0928";
                    }else {
                        if(authorized.startsWith("%")) {
                            authorized = DESCryptoTools.decode(URLDecoder.decode(authorized));
                        }else{
                            authorized = DESCryptoTools.decode(authorized);
                        }
                    }
                    auth = authorized.split(",");
                    s_userid = (auth[0].split("="))[1];
                    s_username = (auth[1].split("="))[1];
                } catch (Exception e) {
                    e.printStackTrace();
                }


                logger.info("调用门户登陆成功！=====================>authorized解密后：" + authorized);

                if (s_username.equalsIgnoreCase(username)) {
                    httpSession.setAttribute(Global.FRONT_SESSION_USERID, s_userid);
                    httpSession.setAttribute(Global.FRONT_SESSION_USERNAME, s_username);
                    SessionUtils.setUser(s_username);
                }
            }
            String userName = (String) httpSession.getAttribute(Global.FRONT_SESSION_USERNAME);
            if (StringUtils.isBlank(userName)) {
                String sss = PropertiesUtil.props.getProperty("serverUrl");
                if (StringUtils.isNotBlank(request.getRequestURI())) {
                    sss += request.getRequestURI();
                }
                if (StringUtils.isNotBlank(request.getQueryString())) {
                    sss += "?" + request.getQueryString();
                }
                logger.info("===============>登陆成功后返回地址(URL编码前):" + sss);
                String tourl = URLEncoder.encode(sss);
                logger.info("===============>登陆成功后返回地址(URL编码后):" + tourl);
                response.sendRedirect(PropertiesUtil.props.getProperty("loginUrl") + "?tourl=" + tourl);
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    /**
     * @see Filter#destroy()
     */
    @Override
    public void destroy() {
    }

    /**
     * 判断是否登陆了
     * @param request
     * @return
     */
    private boolean islogin(HttpServletRequest request) {

        String loginUrl = PropertiesUtil.props.getProperty("loginDir");
        if (org.apache.commons.lang.StringUtils.isBlank(loginUrl)) return false;
        String[] dirs = loginUrl.split(";");
        for (String dir : dirs) {
            System.out.println(request.getRequestURI());
            if (request.getRequestURI().startsWith(dir)) {
                return true;
            }
        }
        return false;
    }
}
